//
//  CouponBeUsedViewController.m
//  P001
//
//  Created by panquanReabam.com on 16/6/2.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "CouponBeUsedViewController.h"
#import "HttpRequest.h"
@interface CouponBeUsedViewController  ()<UITextFieldDelegate,UIGestureRecognizerDelegate ,UIScrollViewDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate>
@end

@implementation CouponBeUsedViewController
{
    UITextField* VerificationCode;
    UIButton*ToObtain;
    UIButton*registdd;
  
}
@synthesize alt = alt;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
    backButton.titleLabel.font=[UIFont systemFontOfSize:13];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"核销券";
    // 手势
    UITapGestureRecognizer *singleFingerOne = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTapDone)];
    singleFingerOne.numberOfTouchesRequired = 1; //手指数
    singleFingerOne.numberOfTapsRequired = 1; //tap次数
    singleFingerOne.delegate = self;
    [self.view addGestureRecognizer:singleFingerOne];
 
    UIView*myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"确定" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:luseColor forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:keyboardFot];
    [btnDone111 addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    
    VerificationCode = [[UITextField alloc] initWithFrame:CGRectMake(15, 50+64, 220, 45)];
    [VerificationCode setBorderStyle:UITextBorderStyleNone]; //外框类型
    VerificationCode.placeholder = @"请输入会员收到的手机验证码"; //默认显示的
    VerificationCode.font = [UIFont systemFontOfSize: 15.0];
    VerificationCode.autocorrectionType = UITextAutocorrectionTypeNo;
    VerificationCode.autocapitalizationType = UITextAutocapitalizationTypeNone;
    VerificationCode.returnKeyType = UIReturnKeyDone;
    //  VerificationCode.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    VerificationCode.delegate = self;
    VerificationCode.tag=2;
    VerificationCode.keyboardType = UIKeyboardTypeDecimalPad;
    [self.view addSubview:VerificationCode];
    VerificationCode.inputAccessoryView = myToolBar;
    ToObtain = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth*930/1240, 60+64, ScreenWidth*245/1240,26)];
    [ToObtain setTitle:@"获取验证码" forState:UIControlStateNormal];
    ToObtain.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    [ToObtain.layer setCornerRadius:3.0]; //设置矩圆角半径
    [ToObtain.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){228/255.0, 228/255.0, 228/255.0, 1.0});
    [ToObtain.layer setBorderColor:tureBTncolorref];//边框颜色
    [ToObtain setTitleColor:[UIColor colorWithRed:249/255.0 green:53/255.0 blue:30/255.0 alpha:1.0]
                   forState:UIControlStateNormal];
    [ToObtain addTarget:self action:@selector(startTime) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ToObtain];
   
    UILabel*lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(10,VerificationCode.bottom, ScreenWidth-20, 0.40)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0f/255.0f green:238.0f/255.0f blue:238.0f/255.0f alpha:1.0f]];
    lineLabel.textColor=[UIColor clearColor];
    [self.view addSubview:lineLabel];

    
    
    
    registdd = [[UIButton alloc] initWithFrame:CGRectMake(10,200+64, ScreenWidth-20, anniuHeigth)];
    [registdd setTitle:@"确定核销" forState:UIControlStateNormal];
    [registdd setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    registdd.backgroundColor=luseColor;
    [registdd.layer setCornerRadius:3.0]; //设置矩圆角半径
    [registdd.layer setBorderWidth:0.3];   //边框宽度
    CGColorSpaceRef tureBTnSpace1 = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref1 = CGColorCreate(tureBTnSpace1,(CGFloat[]){23/255.0,148/255.0, 153/255.0, 1.0});
    [registdd.layer setBorderColor:tureBTncolorref1];//边框颜色
    [registdd addTarget:self action:@selector(regist:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registdd];
}





-(void)startTime{
    
    
            __block int timeout=60; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [ToObtain setTitle:@"获取" forState:UIControlStateNormal];
                        ToObtain.userInteractionEnabled = YES;
                    });
                }else{
                    //            int minutes = timeout / 60;
                    int seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        //                NSLog(@"____%@",strTime);
                        if (strTime.intValue==59) {
                            NSLog(@"____%@",strTime);
                            
                            
                            
                            NSMutableDictionary *params = [NSMutableDictionary new];
                            [params setValue:self.phone forKey:@"mobile"];
                            [params setValue:@"C" forKey:@"msgType"];
                            
                            
                            [HttpRequest requestData:@"System/SendMsg" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                                if (isSuccess) {
                                    NSLog(@"====%@",severDataDict.dataDict);
                                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                                        [Global hideProgressHUDInternal:self.view];
                                        NSString*ResultString=[severDataDict.dataDict objectForKey:@"ResultString"];
                                        [self showAlertMessage:ResultString];
                                        
                                    }else{
                                        [Global hideProgressHUDInternal:self.view];
                            
                                        
                                    }
                                }
                                else
                                {
                                    [Global hideProgressHUDInternal:self.view];
                                    
                                    [Global showTextHudSub:severDataDict.resultStr view:self.view];
                                    
                                    
                                    
                                }
                                
                            }];
                        }
                        
                        if (![strTime isEqualToString:@"00"]) {
                            [ToObtain setTitle:[NSString stringWithFormat:@"%@秒重获",strTime] forState:UIControlStateNormal];
                            
                        }
                        ToObtain.userInteractionEnabled = NO;
                        
                    });
                    timeout--;
                    
                }
            });
            dispatch_resume(_timer);
            
        }
        


-(void)regist:(UIButton*)sender{
    
    
  if ([VerificationCode.text length]<1)
    {
        [self showAlertMessage:@"请输入验证码"];
    }
    
    else{
        
        [Global showIndeterminateHud:@"请稍后。。。" delay:20 view:self.view];
        
        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
        NSString* tokenId = [user1 objectForKey:@"tokenId"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:tokenId forKey:@"tokenId"];
       
        [params setValue:self.snList forKey:@"snList"];
        [params setValue:VerificationCode.text forKey:@"msgCode"];
        
         NSLog(@"====%@",params);
        [HttpRequest requestData:@"Business/Coupon/BeUsed" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                     [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
             
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    [self showAlertMessage:[severDataDict.dataDict objectForKey:@"ResultString"]];
                    
                }
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }];
        
    }
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定哦 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}


- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:2.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)OnTapDone{
 
    [VerificationCode resignFirstResponder];
    
    
    if (VerificationCode.text.length>1) {
        
        
    }
    
}


@end
